package com.ybkj.daijia.api.gexin;

import com.gexin.rp.sdk.base.IPushResult;
import com.gexin.rp.sdk.base.IQueryResult;
import com.gexin.rp.sdk.base.impl.ListMessage;
import com.gexin.rp.sdk.base.impl.SingleMessage;
import com.gexin.rp.sdk.base.impl.Target;
import com.gexin.rp.sdk.base.payload.APNPayload;
import com.gexin.rp.sdk.http.IGtPush;
import com.gexin.rp.sdk.template.LinkTemplate;
import com.gexin.rp.sdk.template.NotificationTemplate;
import com.gexin.rp.sdk.template.TransmissionTemplate;
import com.ybkj.daijia.PushData;
import com.ybkj.daijia.Setting;
import com.ybkj.daijia.server.mc.Passenger;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class GeTuiMember {

    private static final Logger logger = LoggerFactory.getLogger(GeTuiMember.class);


    private static String Host = "http://sdk.open.api.igexin.com/apiex.htm";

    private static String Host2 = "http://sdk.open.api.igexin.com/api.htm";


    public static void push(Passenger passenger, PushData pushData, Setting setting)
        throws IOException {

        String userId = passenger.getCid();

        String AppID = setting.getGetuiMemberAppID();
        String AppKey = setting.getGetuiMemberAppKey();
        String Master = setting.getGetuiMemberMaster();

        IGtPush push = new IGtPush(Host, AppKey, Master);
        push.connect();

        SingleMessage message = new SingleMessage();
        message.setOffline(true);
        //离线有效时间，单位为毫秒
        message.setOfflineExpireTime(1 * 3600 * 1000);

        Target target1 = new Target();

        target1.setAppId(AppID);
        target1.setClientId(userId);

        if (Passenger.DEVICE_ANDROID.equals(passenger.getDeviceType())) {
            TransmissionTemplate template = TransmissionTemplateDemo(pushData, AppID, AppKey);
            message.setData(template);
        } else if (Passenger.DEVICE_IOS.equals(passenger.getDeviceType())) {
            TransmissionTemplate template = TransmissionTemplateDemo(pushData, AppID, AppKey);
            message.setData(template);
        } else {
            //TODO 其他设备的推送
            if (StringUtils.isNotBlank(passenger.getDeviceType())) {
                logger.warn("This DeviceType:{} not support yet.", passenger.getDeviceType());
            }
        }

        try {

            IPushResult ret = push.pushMessageToSingle(message, target1);

            logger.debug("push response : " + ret.getResponse().toString());

        } catch (Exception e) {
            logger.error("{}", e);
        }

    }

    public static void notice(Passenger passenger, PushData pushData, Setting setting)
        throws IOException {

        String userId = passenger.getCid();

        String AppID = setting.getGetuiMemberAppID();
        String AppKey = setting.getGetuiMemberAppKey();
        String Master = setting.getGetuiMemberMaster();

        IGtPush push = new IGtPush(Host, AppKey, Master);
        push.connect();

        LinkTemplate template = linkTemplateDemo(pushData, AppID, AppKey);
        SingleMessage message = new SingleMessage();
        message.setOffline(true);

        message.setOfflineExpireTime(1 * 3600 * 1000);
        message.setData(template);

        Target target1 = new Target();

        target1.setAppId(AppID);
        target1.setClientId(userId);

        try {

            IPushResult ret = push.pushMessageToSingle(message, target1);
            logger.debug("notice response : " + ret.getResponse().toString());

        } catch (Exception e) {
            logger.error("{}", e);
        }

    }

    public static void noticeList(List<Passenger> passengers, PushData pushData, Setting setting)
        throws IOException {

        String AppID = setting.getGetuiMemberAppID();
        String AppKey = setting.getGetuiMemberAppKey();
        String Master = setting.getGetuiMemberMaster();

        IGtPush push = new IGtPush(Host, AppKey, Master);
        push.connect();

        NotificationTemplate template = NotificationTemplateDemo(pushData, AppID, AppKey);
        ListMessage message = new ListMessage();

        message.setData(template);
        message.setOffline(true);
        message.setOfflineExpireTime(1 * 3600 * 1000);

        List targets = new ArrayList();

        for (Passenger passenger : passengers) {
            String cid = passenger.getCid();
            if (StringUtils.isNotBlank(cid)) {
                Target target1 = new Target();
                target1.setAppId(AppID);
                target1.setClientId(cid);
                targets.add(target1);
            }
        }

        try {
            //获取taskID
            String taskId = push.getContentId(message);
            logger.debug("noticeList taskId : " + taskId);
            //使用taskID对目标进行推送
            IPushResult ret = push.pushMessageToList(taskId, targets);
            //打印服务器返回信息
            logger.debug("noticeList response : " + ret.getResponse().toString());

        } catch (Exception e) {
            logger.error("{}", e);
        }

    }

    public static void message(Passenger passenger, PushData pushData, Setting setting)
        throws IOException {

        String userId = passenger.getCid();

        String AppID = setting.getGetuiMemberAppID();
        String AppKey = setting.getGetuiMemberAppKey();
        String Master = setting.getGetuiMemberMaster();

        IGtPush push = new IGtPush(Host, AppKey, Master);
        push.connect();

        NotificationTemplate template = NotificationTemplateDemo(pushData, AppID, AppKey);
        SingleMessage message = new SingleMessage();
        message.setOffline(true);

        message.setOfflineExpireTime(1 * 3600 * 1000);
        message.setData(template);

        Target target1 = new Target();

        target1.setAppId(AppID);
        target1.setClientId(userId);

        try {

            IPushResult ret = push.pushMessageToSingle(message, target1);
            logger.debug("message response : " + ret.getResponse().toString());

        } catch (Exception e) {
            logger.error("{}", e);
        }


    }

    public static LinkTemplate linkTemplateDemo(PushData pushData, String AppID, String AppKey) {

        LinkTemplate template = new LinkTemplate();
        // 设置APPID与APPKEY
        template.setAppId(AppID);
        template.setAppkey(AppKey);
        // 设置通知栏标题与内容
        template.setTitle(pushData.getTitle());
        template.setText(pushData.getDescription());
        // 配置通知栏图标
        template.setLogo("lg_launcher.png");
        // 配置通知栏网络图标
        template.setLogoUrl("");
        // 设置通知是否响铃，震动，或者可清除
        template.setIsRing(true);
        template.setIsVibrate(true);
        template.setIsClearable(true);
        // 设置打开的网址地址
        template.setUrl(pushData.getLink());
        return template;
    }

    public static TransmissionTemplate TransmissionTemplateDemo(PushData pushData, String AppID,
        String AppKey) {

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("title", pushData.getTitle());
        jsonObject.put("type", pushData.getType());
        jsonObject.put("description", pushData.getDescription());
        jsonObject.put("data", pushData.getData());

        TransmissionTemplate template = new TransmissionTemplate();
        template.setAppId(AppID);
        template.setAppkey(AppKey);
        template.setTransmissionType(2);
        template.setTransmissionContent(jsonObject.toString());

        APNPayload payload = new APNPayload();
        payload.setBadge(1);  //将应用icon上显示的数字设为1
        //在已有数字基础上加1显示，设置为-1时，在已有数字上减1显示，设置为数字时，如10，效果和setBadge一样，
        //应用icon上显示指定数字。不能和setBadge同时使用
        //setAutoBadge("+1");
        payload.setContentAvailable(1);
//        payload.setSound("default");
//        payload.setCategory("$由客户端定义");
        //简单模式APNPayload.SimpleMsg 
        payload.setAlertMsg(new APNPayload.SimpleAlertMsg(pushData.getDescription()));
        payload.addCustomMsg("msg", jsonObject.toString());
        //字典模式使用下者
        //payload.setAlertMsg(getDictionaryAlertMsg());
        template.setAPNInfo(payload);

        return template;

    }

    public static NotificationTemplate NotificationTemplateDemo(PushData pushData, String AppID,
        String AppKey) {
        NotificationTemplate template = new NotificationTemplate();
        // 设置APPID与APPKEY
        template.setAppId(AppID);
        template.setAppkey(AppKey);
        // 设置通知栏标题与内容
        template.setTitle(pushData.getTitle());
        template.setText(pushData.getDescription());
        // 配置通知栏图标
        template.setLogo("lg_launcher.png");
        // 配置通知栏网络图标
        template.setLogoUrl("");
        // 设置通知是否响铃，震动，或者可清除
        template.setIsRing(true);
        template.setIsVibrate(true);
        template.setIsClearable(true);

        template.setTransmissionType(1);
        return template;
    }

    public static String getClientStatus(String userId, Setting setting) throws IOException {

        String AppID = setting.getGetuiMemberAppID();
        String AppKey = setting.getGetuiMemberAppKey();
        String Master = setting.getGetuiMemberMaster();

        try {

            IGtPush push = new IGtPush(Host, AppKey, Master);
            IQueryResult abc = push.getClientIdStatus(AppID, userId);

            return abc.getResponse().get("result").toString();

        } catch (Exception e) {
            logger.error("{}", e);
            return "Error";
        }

    }

//	public static void main(String[] args) {
//	  
//	  String AppID =  "HRoxdeIx2X9CsB9WSJb903";
//      String AppKey = "KPIVreC9xV7BWOblsEGL28";
//      String Master = "q1TDlRMGA36aeFpj0nmn54";
//      
//      try {
//          
//          IGtPush push = new IGtPush(Host, AppKey, Master);
//          IQueryResult abc = push.getClientIdStatus(AppID, "36376da2a0da7c22971758a1efc18be6");
//
//                  
//      } catch (Exception e) {
//          logger.error("{}",e);
//      }
//      
//    }

}

